package com.cloudfun.campusshare.schedule;

import com.cloudfun.campusshare.common.constant.UserCouponStatus;
import com.cloudfun.campusshare.entity.UserCouponEntity;
import com.cloudfun.campusshare.repo.UserCouponRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by Huqin on 2020/6/1
 */
@Slf4j
@Component
public class UserCouponStatusChangeSchedule extends BaseScheduleTask {

    @Autowired
    private UserCouponRepo userCouponRepo;

    /**
     * 每1分钟执行一次
     */
    @Scheduled(fixedRate = 60 * 1000)
    public void changeBidStatus() {
        this.execute();
    }

    @Override
    protected String getTaskName() {
        return "已领取代金券状态更新";
    }

    @Override
    protected void doExecute() {
        LocalDateTime now = LocalDateTime.now();
        List<UserCouponEntity> userCouponEntities = userCouponRepo.findAllByStatus(UserCouponStatus.NOT_USED);
        for (UserCouponEntity userCouponEntity : userCouponEntities) {
            LocalDateTime endTime = userCouponEntity.getEndTime();
            if (endTime.isBefore(now)) {
                userCouponEntity.setStatus(UserCouponStatus.EXPIRED);
            }
        }
        userCouponRepo.saveAll(userCouponEntities);
    }

}
